<template>
  <ArtTableFullScreen>
    <div id="table-full-screen">
      <el-card shadow="never" class="art-table-card">
        <ArtTableHeader
          :columnList="columnOptions"
          v-model:columns="columnChecks"
          @refresh="handleRefresh"
        >
          <template #left>
            <el-row :gutter="24">
              <el-col :span="12">
                <el-button @click="showDialog('add')" :icon="Plus">新增</el-button>
              </el-col>
              <el-upload action="" :before-upload="onBeforeUpload" multiple :show-file-list="false">
                <el-button type="primary">上传apk包</el-button>
              </el-upload>
            </el-row>
          </template>
        </ArtTableHeader>
        <art-table
          :data="tableData"
          :loading="loading"
          :currentPage="queryParams.page"
          :pageSize="queryParams.size"
          :total="total"
          @size-change="getTableData"
          @current-change="getTableData"
        >
          <template #default>
            <el-table-column v-for="col in columns" :key="col.prop" v-bind="col" />
          </template>
        </art-table>

        <el-dialog
          v-model="dialogVisible"
          :title="dialogType === 'add' ? '新增参数' : '修改参数'"
          width="40%"
        >
          <el-form ref="formRef" :model="formData" :rules="rules" label-width="80px">
            <el-form-item label="参数名称" prop="name">
              <el-input v-model="formData.name" placeholder="请输入参数名称" />
            </el-form-item>
            <el-form-item label="参数值" prop="value">
              <el-input v-model="formData.value" placeholder="请输入参数值" />
            </el-form-item>
            <el-form-item label="描述" prop="desc">
              <el-input type="textarea" v-model="formData.desc" placeholder="请输入描述" />
            </el-form-item>
          </el-form>
          <template #footer>
            <div class="dialog-footer">
              <el-button @click="dialogVisible = false">取消</el-button>
              <el-button type="primary" @click="handleSubmit">提交</el-button>
            </div>
          </template>
        </el-dialog>
      </el-card>
      <el-dialog
        top="36vh"
        class="my-dialog"
        v-model="progressOpen"
        append-to-body
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        :show-close="false"
      >
        <el-progress type="circle" :percentage="percentage" text-color="#20A0FF"></el-progress>
        <div style="color: #20a0ff">上传中...</div>
      </el-dialog>
    </div>
  </ArtTableFullScreen>
</template>

<script setup lang="ts">
  import { h } from 'vue'
  import { FormInstance } from 'element-plus'
  import { ElMessage, ElButton } from 'element-plus'
  import type { FormRules } from 'element-plus'
  import { ConfigService } from '@/api/common/config'
  import { Plus, Edit } from '@element-plus/icons-vue'
  import { useCheckedColumns } from '@/composables/useCheckedColumns'
  import { uploadObject } from '@/utils/uploadFile.js'

  const dialogType = ref('add')
  const dialogVisible = ref(false)
  const loading = ref(false)
  const total = ref(0)
  const tableData = ref<any>([])

  const formData = reactive({
    name: '',
    value: '',
    desc: ''
  })

  const queryParams = reactive({
    page: 1,
    size: 10
  })
  // 列配置
  const columnOptions = [
    { label: 'ID', prop: 'id' },
    { label: '参数名称', prop: 'name' },
    { label: '参数值', prop: 'value' },
    { label: '描述', prop: 'desc' },
    { label: '操作', prop: 'operation' }
  ]

  // 动态列配置
  const { columnChecks, columns } = useCheckedColumns(() => [
    { prop: 'id', label: 'ID' },
    { prop: 'name', label: '参数名称' },
    { prop: 'value', label: '参数值' },
    { prop: 'desc', label: '描述' },
    {
      prop: 'operation',
      label: '操作',
      align: 'center',
      fixed: 'right', // 固定在右侧
      formatter: (row: any) => {
        return h('div', { class: 'option' }, [
          h(
            ElButton,
            {
              size: 'small',
              icon: Edit,
              text: true,
              onClick: () => showDialog('edit', row)
            },
            () => '编辑'
          )
        ])
      }
    }
  ])

  onMounted(() => {
    getTableData()
  })

  const handleRefresh = () => {
    getTableData()
  }
  // 获取商品列表
  const getTableData = async () => {
    loading.value = true
    const res = await ConfigService.getConfigList(queryParams)
    total.value = res.data.total
    tableData.value = res.data.data
    loading.value = false
  }

  const showDialog = (type: string, row?: any) => {
    if (type === 'edit' && row) {
      formData.name = row.name
      formData.value = row.value
      formData.desc = row.desc
      formData.id = row.id
    } else {
      formData.name = ''
      formData.value = ''
      formData.desc = ''
      formData.id = ''
    }
    dialogVisible.value = true
    dialogType.value = type
  }

  const rules = reactive<FormRules>({
    name: [{ required: true, message: '请选择参数名称', trigger: 'blur' }],
    value: [{ required: true, message: '请输入参数值', trigger: 'blur' }],
    desc: [{ required: true, message: '请输入描述', trigger: 'blur' }]
  })

  const formRef = ref<FormInstance>()

  const handleSubmit = async () => {
    if (!formRef.value) return

    await formRef.value.validate((valid) => {
      if (valid) {
        if (dialogType.value === 'add') {
          ConfigService.addConfig(formData)
        } else {
          ConfigService.updateConfig(formData)
        }
        ElMessage.success(dialogType.value === 'add' ? '添加成功' : '更新成功')
        getTableData()
        dialogVisible.value = false
      }
    })
  }
  const percentage = ref(0)
  const progressOpen = ref(false)
  // 上传之前的回调
  const onBeforeUpload = (file: any) => {
    uploadObject(file, 2, (res) => {
      percentage.value = parseFloat(res.percent) * 100
      progressOpen.value = true
    }).then(() => {
      ElMessage.success('上传成功')
      progressOpen.value = false
    })
    return false
  }
</script>

<style lang="scss">
  :deep(.option .el-button + .el-button) {
    margin-left: 0;
  }
  .my-dialog {
    background: transparent;
    -webkit-box-shadow: none;
    box-shadow: none;
    border: none;
    .el-dialog__body {
      text-align: center;
    }
  }
</style>
